<template>
  <div
    ref="container"
    class="container relative bg-gray-900 mx-auto text-gray-100"
    style="max-width: 960px"
  >
    <Modal
      v-if="content"
      :clearContent="clearContent"
      :content="content"
      @click.native.self="clearContent"
    />
    <transition name="drop">
      <div
        v-if="inView || showPreview"
        class="
          fixed
          top-0
          w-full
          z-30
          bg-gray-900
          justify-between
          items-center
          flex
          md:hidden
        "
      >
        <div
          class="logo w-16 m-4"
          v-html="require(`~/assets/icons/logo.svg?include`)"
        ></div>
        <button
          :class="showPreview ? 'bg-gray-700' : 'bg-emerald-600'"
          class="
            p-3
            mx-4
            font-extrabold
            rounded
            tracking-wide
            focus:outline-none
            select-none
          "
          @click="!opening && togglePreview()"
        >
          {{ showPreview ? '关闭预览' : '打开预览' }}
        </button>
      </div>
    </transition>
    <transition name="fade">
      <Preview
        v-show="showPreview"
        ref="html"
        :PreviewMode="PreviewMode"
        :colors="colors"
        :downloadKey="downloadKey"
        :downloadVcard="downloadVcard"
        :featured="featured"
        :footerCredit="footerCredit"
        :genInfo="genInfo"
        :hasLightBG="hasLightBG"
        :images="images"
        :primaryActions="primaryActions"
        :pubKeyIsValid="pubKeyIsValid"
        :secondaryActions="secondaryActions"
        :showAlert="showAlert"
        :username="username"
        class="fixed top-20 w-full bottom-0 z-20 border-none rounded-b-none"
      />
    </transition>


    <div class="md:grid md:grid-cols-2">
      <div class="px-4 mt-32">
        <div id="step-1" ref="create" class="pt-8">
          <h2 class="font-extrabold text-2xl">Header attachments</h2>
          <div class="stepC">
            <Attachment
              :content="images"
              :resizeImage="resizeImage"
              :showAlert="showAlert"
              description="建议格式: svg, png 或 gif"
              label="添加商标"
              type="logo"
            />
            <Attachment
              :content="images"
              :resizeImage="resizeImage"
              :showAlert="showAlert"
              description="建议格式: svg, jpeg, png, gif, mp4, webm 或 mov"
              label="添加封面照片/视频"
              type="cover"
            />
            <p class="mt-6 border p-4 rounded border-gray-700 text-gray-400">
              推荐的封面照片/视频尺寸为 960 x 540 像素，宽高比为 16:9
            </p>
          </div>
        </div>
        <div id="step-2" class="mt-16">
          <h2 class="font-extrabold text-2xl">联系信息</h2>
          <Attachment
            :content="images"
            :resizeImage="resizeImage"
            :showAlert="showAlert"
            description="建议格式: jpeg, png 或 gif"
            label="添加个人照片"
            type="photo"
          />
          <p class="mt-6 border p-4 rounded border-gray-700 text-gray-400">
            推荐的个人照片尺寸为 320 x 320 像素，宽高比为 1:1
          </p>
          <div class="stepC mt-6 grid grid-cols-2 gap-4">
            <div>
              <label class="ml-4" for="firstname">名称前缀</label>
              <input
                id="firstname"
                v-model="genInfo.fname"
                autocapitalize="words"
                class="
                  mt-2
                  px-4
                  w-full
                  h-12
                  bg-black
                  rounded
                  border border-transparent
                  transition-colors
                  duration-200
                  focus:outline-none focus:border-gray-600
                  hover:border-gray-600
                "
                spellcheck="false"
                type="text"
              />
            </div>
            <div>
              <label class="ml-4" for="lastname">名称后缀</label>
              <input
                id="lastname"
                v-model="genInfo.lname"
                autocapitalize="words"
                class="
                  mt-2
                  px-4
                  w-full
                  h-12
                  bg-black
                  rounded
                  border border-transparent
                  transition-colors
                  duration-200
                  focus:outline-none focus:border-gray-600
                  hover:border-gray-600
                "
                spellcheck="false"
                type="text"
              />
            </div>
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="pronouns">职位</label>
            <input
              id="pronouns"
              v-model="genInfo.pronouns"
              autocapitalize="words"
              class="
                mt-2
                px-4
                w-full
                h-12
                bg-black
                placeholder-gray-600
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                hover:border-gray-600
              "
              placeholder="他/他的"
              spellcheck="false"
              type="text"
            />
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="job-title">联系人姓名</label>
            <input
              id="job-title"
              v-model="genInfo.title"
              autocapitalize="words"
              class="
                mt-2
                px-4
                w-full
                h-12
                bg-black
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                hover:border-gray-600
              "
              spellcheck="true"
              type="text"
            />
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="business-name">联系方式</label>
            <input
              id="business-name"
              v-model="genInfo.biz"
              autocapitalize="words"
              class="
                mt-2
                px-4
                w-full
                h-12
                bg-black
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                hover:border-gray-600
              "
              spellcheck="false"
              type="text"
            />
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="business-address">公司地址</label>
            <textarea
              id="business-address"
              :value="genInfo.addr"
              class="
                block
                mt-2
                px-4
                py-3
                w-full
                bg-black
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                resize-none
                hover:border-gray-600
              "
              rows="4"
              @input="genInfo.addr = $event.target.value"
            ></textarea>
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="business-description"
            >公司描述
            </label>
            <textarea
              id="business-description"
              :value="genInfo.desc"
              class="
                block
                mt-2
                px-4
                py-3
                w-full
                bg-black
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                resize-none
                hover:border-gray-600
              "
              rows="4"
              @input="genInfo.desc = $event.target.value"
            ></textarea>
          </div>
          <!--          <div class="stepC relative mt-6">-->
          <!--            <label for="pgp-public-key" class="flex justify-between ml-4"-->
          <!--              >OpenPGP 公钥<span-->
          <!--                v-if="genInfo.key"-->
          <!--                class="mr-4"-->
          <!--                :class="pubKeyIsValid ? 'text-emerald-500' : 'text-red-600'"-->
          <!--                >{{ pubKeyIsValid ? '有效' : '无效模式' }}</span-->
          <!--              >-->
          <!--            </label>-->
          <!--            <textarea-->
          <!--              id="pgp-public-key"-->
          <!--              v-model="genInfo.key"-->
          <!--              class="-->
          <!--                block-->
          <!--                mt-2-->
          <!--                px-4-->
          <!--                py-3-->
          <!--                w-full-->
          <!--                bg-black-->
          <!--                placeholder-gray-600-->
          <!--                rounded-->
          <!--                border border-transparent-->
          <!--                transition-colors-->
          <!--                duration-200-->
          <!--                focus:outline-none focus:border-gray-600-->
          <!--                resize-none-->
          <!--                hover:border-gray-600-->
          <!--              "-->
          <!--              rows="4"-->
          <!--              spellcheck="false"-->
          <!--              placeholder="在此粘贴公钥区块"-->
          <!--            ></textarea>-->
          <!--          </div>-->
        </div>
        <div id="step-3" class="mt-16">
          <h2 class="font-extrabold text-2xl">主要操作</h2>
          <draggable
            v-model="primaryActions"
            animation="1"
            ghostClass="ghost"
            handle=".drag"
          >
            <transition-group name="list" type="transition">
              <Action
                v-for="(item, index) in primaryActions"
                :key="'item' + index"
                :buttonBg="colors.buttonBg.color"
                :index="index"
                :item="item"
                :removeAction="removeAction"
                :type="primaryActions"
                name="primaryActions"
              />
            </transition-group>
          </draggable>
          <div
            :class="{ 'border-t pt-6': primaryActions.length }"
            class="mt-6 border-gray-800"
          >
            <input
              v-model="filterPrimary"
              class="
                px-4
                mb-2
                w-full
                h-12
                bg-black
                placeholder-gray-600
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                hover:border-gray-600
              "
              placeholder="搜索操作"
              spellcheck="false"
              type="text"
              @keydown.esc="clearFilterActions"
              @keypress.enter="
                filteredAction('filteredPrimaryActions', 'primaryActions')
              "
            />
            <!--            <p class="p-3" v-if="filteredPrimaryActions.length < 1">-->
            <!--              找不到操作？请-->
            <!--              <a-->
            <!--                href="#help"-->
            <!--                class="-->
            <!--                  cursor-pointer-->
            <!--                  underline-->
            <!--                  font-extrabold-->
            <!--                  text-emerald-600-->
            <!--                  hover:text-emerald-500-->
            <!--                  focus:text-emerald-500-->
            <!--                  transition-colors-->
            <!--                  duration-200-->
            <!--                "-->
            <!--                >在 Telegram 上留下你的建议</a-->
            <!--              >-->
            <!--            </p>-->
            <div class="stepC actions">
              <button
                v-for="(action, index) in filteredPrimaryActions"
                :key="index"
                :aria-label="action.name"
                :title="
                  action.name.substr(0, 1).toUpperCase() + action.name.slice(1)
                "
                class="
                  p-3
                  flex
                  items-center
                  shrink-0
                  rounded
                  hover:bg-gray-600
                  focus:bg-gray-600
                  transition-colors
                  duration-200
                  focus:outline-none
                  bg-gray-700
                "
                @click="addAction('primaryActions', action.name)"
              >
                <div
                  class="w-6 h-6 mr-3 shrink-0"
                  v-html="require(`~/assets/icons/${action.icon}.svg?include`)"
                ></div>
                <p class="whitespace-nowrap">
                  {{
                    action.name.substr(0, 1).toUpperCase() +
                    action.name.slice(1)
                  }}
                </p>
              </button>
            </div>
          </div>
        </div>
        <div id="step-5" class="mt-16">
          <h2 class="font-extrabold text-2xl">特色内容</h2>
          <div class="stepC">
            <draggable
              v-model="featured"
              animation="1"
              ghostClass="ghost"
              handle=".drag"
            >
              <transition-group name="list" type="transition">
                <Featured
                  v-for="(content, index) in featured"
                  :key="'content' + index"
                  :featured="featured"
                  :index="index"
                  :resizeImage="resizeImage"
                  :showAlert="showAlert"
                  mimetypes="image/jpeg, image/png, audio/mpeg, video/mp4, video/webm, application/pdf"
                />
              </transition-group
              >
            </draggable>

            <div class="flex mt-6">
              <div class="flex flex-wrap items-center">
                <button
                  aria-label="Add section"
                  class="
                    p-3
                    rounded
                    bg-gray-700
                    hover:bg-gray-600
                    focus:bg-gray-600
                    transition-colors
                    duration-200
                    focus:outline-none
                  "
                  @click="addFeature()"
                >
                  <div
                    class="w-6 h-6"
                    v-html="require(`~/assets/icons/add.svg?include`)"
                  ></div>
                </button>
                <p class="ml-3 leading-none">添加部分</p>
              </div>
            </div>
            <p class="mt-6 border p-4 rounded border-gray-700 text-gray-400">
              支持的媒体格式: jpeg, png, mp3, mp4, webm 和 pdf
            </p>
          </div>
        </div>
        <div id="step-6" class="mt-16">
          <h2 class="font-extrabold text-2xl">加载配置</h2>
          <div class="stepC">
            <!-- 加载配置内容将在这里添加 -->
            <MediaUpload
              :content="images"
              :showAlert="showAlert"
              description="建议格式: jpeg, png 或 gif"
              label="添加加载时背景图片"
              type="background"
            />
            <p class="mt-6 border p-4 rounded border-gray-700 text-gray-400">
              推荐的个人照片尺寸为 960 x 540 像素，高宽比为 16:9
            </p>
          </div>
        </div>
        <div id="step-7" class="mt-16">
          <h2 class="font-extrabold text-2xl">主题</h2>
          <div class="stepC mt-3 flex flex-wrap">
            <button
              :class="
                theme == 1
                  ? 'bg-emerald-600'
                  : 'bg-gray-700 hover:bg-gray-600 focus:bg-gray-600'
              "
              class="
                w-12
                h-12
                rounded
                mt-3
                mr-3
                font-extrabold
                focus:outline-none
                transition-colors
                duration-200
              "
              @click="changeTheme(1)"
            >
              A
            </button>
            <button
              :class="
                theme == 2
                  ? 'bg-emerald-600'
                  : 'bg-gray-700 hover:bg-gray-600 focus:bg-gray-600'
              "
              class="
                w-12
                h-12
                rounded
                mt-3
                mr-3
                font-extrabold
                focus:outline-none
                transition-colors
                duration-200
              "
              @click="changeTheme(2)"
            >
              B
            </button>
            <button
              :class="
                theme == 3
                  ? 'bg-emerald-600'
                  : 'bg-gray-700 hover:bg-gray-600 focus:bg-gray-600'
              "
              class="
                w-12
                h-12
                rounded
                mt-3
                mr-3
                font-extrabold
                focus:outline-none
                transition-colors
                duration-200
              "
              @click="changeTheme(3)"
            >
              C
            </button>
          </div>
        </div>
        <div id="step-8" class="mt-16">
          <h2 class="font-extrabold text-2xl">颜色</h2>
          <div class="stepC">
            <Colour :colors="colors" label="头部背景" name="logoBg" />
            <Colour :colors="colors" label="主背景" name="mainBg" />
            <Colour
              :colors="colors"
              label="按钮背景"
              name="buttonBg"
            />
            <Colour
              :colors="colors"
              label="特色内容背景"
              name="cardBg"
            />
          </div>
        </div>
        <div id="step-9" class="mt-16">
          <h2 class="font-extrabold text-2xl">字体</h2>
          <div class="stepC mt-6">
            <label class="ml-4" for="font-link">网页字体嵌入代码</label>
            <textarea
              id="font-link"
              v-model="genInfo.fontLink"
              :placeholder="`<link href=&quot;https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap&quot; rel=&quot;stylesheet&quot;>`"
              class="
                block
                mt-2
                px-4
                py-3
                w-full
                bg-black
                placeholder-gray-600
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                resize-none
                hover:border-gray-600
              "
              rows="4"
              spellcheck="false"
            ></textarea>
          </div>
          <div class="stepC mt-6">
            <label class="ml-4" for="font-css">Web font CSS rule</label>
            <input
              id="font-css"
              v-model="genInfo.fontCss"
              :placeholder="`font-family: 'Poppins', sans-serif;`"
              class="
                block
                mt-2
                px-4
                py-3
                w-full
                bg-black
                placeholder-gray-600
                rounded
                border border-transparent
                transition-colors
                duration-200
                focus:outline-none focus:border-gray-600
                resize-none
                hover:border-gray-600
              "
              spellcheck="false"
              type="text"
            />
          </div>
          <p class="mt-6 border p-4 rounded border-gray-700 text-gray-400">
            支持的服务包括 Google Fonts、Adobe Typekit 等。请确保从同一字体系列获取常规和粗体字体变体的嵌入代码。
          </p>
        </div>
        <div class="flex justify-center mt-12 mb-8">
          <button
            class="w-48 bg-gray-700 leading-none text-lg tracking-wide border-2 border-transparent font-bold py-3 px-6 rounded select-none transition-colors duration-200 focus:outline-none hover:bg-gray-600"
            @click="saveValue"
          >
            {{ id ? '更新' : '保存' }}
          </button>
        </div>
      </div>
      <div
        id="preview-container"
        class="relative w-full mt-20 sm:mt-0 hidden md:block"
      >
        <div
          id="preview"
          class="
            flex flex-col
            items-center
            justify-center
            sm:sticky sm:top-0
            md:mx-6
            lg:mx-12
          "
        >
          <div id="device" class="bg-black rounded sm:mt-10">
            <h2 class="text-center py-4 font-extrabold text-gray-200">
              LIVE PREVIEW
            </h2>
            <div id="browserFrame" class="overflow-hidden flex flex-col">
              <div
                id="topBar"
                class="
                  topbar
                  border-r-4 border-l-4 border-black
                  bg-gray-900
                  z-10
                "
              >
                <div id="searchField" class="p-2 flex items-center">
                  <input
                    :value="'https://yoursite/vcard/' + username"
                    aria-label="vCard URL"
                    class="pl-4 h-12 w-full bg-black rounded text-gray-500"
                    disabled
                    tabindex="-1"
                    type="text"
                  />
                  <div
                    class="w-6 ml-2"
                    v-html="require(`~/assets/icons/ellipsis.svg?include`)"
                  ></div>
                </div>
              </div>
              <Preview
                ref="html"
                :PreviewMode="PreviewMode"
                :colors="colors"
                :downloadKey="downloadKey"
                :downloadVcard="downloadVcard"
                :featured="featured"
                :footerCredit="footerCredit"
                :genInfo="genInfo"
                :hasLightBG="hasLightBG"
                :images="images"
                :primaryActions="primaryActions"
                :pubKeyIsValid="pubKeyIsValid"
                :secondaryActions="secondaryActions"
                :showAlert="showAlert"
                :username="username"
                class="rounded-b-2xl"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <Vcard ref="vCard" :vCard="vCard" />
  </div>
</template>

<script>
// import JSZip from 'jszip'

import { saveAs } from 'file-saver'
import { mapActions, mapState } from 'vuex'
import { cardService } from '~/services/cardService'
import axios from 'axios'
import { uploadConfig } from '~/services/api.config'

export default {
  name: 'EditCard',
  ssr: false,
  components: {
    Cropper: () => import('~/components/Cropper.vue'),
    Modal: () => import('~/components/Modal.vue'),
    Attachment: () => import('~/components/Attachment.vue'),
    MediaUpload: () => import('~/components/MediaUpload.vue'),
    Action: () => import('~/components/Action.vue'),
    Featured: () => import('~/components/Featured.vue'),
    Colour: () => import('~/components/Colour.vue'),
    Preview: () => import('~/components/Preview.vue'),
    Download: () => import('~/components/Download.vue'),
    Help: () => import('~/components/Help.vue'),
    Footer: () => import('~/components/Footer.vue'),
    Vcard: () => import('~/components/Vcard.vue'),
    draggable: () => import('vuedraggable')
  },

  data() {
    return {
      id: null,
      downloadCheckList: [
        {
          label:
            '我没有附加任何可能对用户造成风险的链接或文件',
          checked: false
        }
      ],
      images: {
        logo: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        photo: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        cover: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        background: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        }
      },
      colors: {
        logoBg: {
          color: `#059669`,
          openPalette: false
        },
        mainBg: {
          color: `#ddd`,
          openPalette: false
        },
        buttonBg: {
          color: `#059669`,
          openPalette: false
        },
        cardBg: {
          color: `#fff`,
          openPalette: false
        }
      },
      genInfo: {
        fname: null,
        lname: null,
        pronouns: null,
        title: null,
        biz: null,
        addr: null,
        desc: null,
        key: null,
        tracker: null,
        fontLink: null,
        fontCss: null
      },
      primaryActions: [],
      filterPrimary: '',
      secondaryActions: [],
      filterSecondary: '',
      actions: {
        primaryActions: [
        {
            name: '手机号码',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: '手机号码',
            order: 0,
            isURL: 0
          },
          {
            name: '办公室',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: '办公室号码',
            order: 1,
            isURL: 0
          },
          {
            name: '家庭',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: '家庭号码',
            order: 2,
            isURL: 0
          },
          {
            name: '短信',
            icon: 'sms',
            href: 'sms:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: '短信手机号码',
            order: 3,
            isURL: 0
          },
          {
            name: '电子邮件',
            icon: 'email',
            href: 'mailto:',
            placeholder: 'info@example.com',
            value: null,
            label: '电子邮件地址',
            order: 4
          },
          {
            name: '网站',
            icon: 'website',
            placeholder: 'https://example.com',
            value: null,
            label: '网站URL',
            order: 5,
            isURL: 1
          },
          {
            name: '游玩攻略',
            icon: 'calendar',
            placeholder: 'https://example.com/storeID',
            value: null,
            label: '在线商店URL',
            order: 6,
            isURL: 1
          },
          {
            name: '导航地图',
            icon: 'location',
            placeholder: 'https://osm.org/go/location',
            value: null,
            label: '地图位置URL',
            order: 7,
            isURL: 1
          },

          {
            name: '企业愿景',
            icon: 'panorama',
            placeholder: 'https://example.com/panorama',
            value: null,
            label: '企业愿景',
            order: 8,
            isURL: 1
          },
          {
            name: '案例展示',
            icon: 'calendar',
            placeholder: 'https://example.com/panorama',
            value: null,
            label: '案例展示',
            order: 8,
            isURL: 1
          },
          {
            name: '电报',
            icon: 'telegram',
            href: 'https://t.me/',
            placeholder: '用户名',
            value: null,
            label: '电报用户名',
            order: 9,
            isURL: 1
          },
          {
            name: '矩阵',
            icon: 'matrix',
            href: 'https://matrix.to/#/',
            placeholder: '@用户名:matrix.org',
            value: null,
            label: '矩阵用户ID',
            order: 10,
            isURL: 1
          },
          {
            name: 'WhatsApp',
            icon: 'whatsapp',
            placeholder: 'https://wa.me/profileID',
            value: null,
            label: 'WhatsApp个人资料URL',
            order: 11,
            isURL: 1
          },
          {
            name: 'Messenger',
            icon: 'messenger',
            href: 'https://m.me/',
            placeholder: '用户名',
            value: null,
            label: 'Messenger用户名',
            order: 12,
            isURL: 1
          },
          {
            name: 'Skype',
            icon: 'skype',
            href: 'skype:',
            hrefEnd: '?chat',
            placeholder: '用户名',
            value: null,
            label: 'Skype用户名',
            order: 13,
            isURL: 1
          },
          {
            name: 'Line',
            icon: 'line',
            href: 'https://line.me/ti/p/',
            placeholder: 'LINE ID',
            value: null,
            label: 'Line个人资料ID',
            order: 14,
            isURL: 1
          },
          // {
          //   name: 'Viber',
          //   icon: 'viber',
          //   href: 'viber://chat?number=',
          //   placeholder: 'XX XXXXX XXXXX',
          //   value: null,
          //   label: 'Viber手机号码',
          //   order: 15,
          //   isURL: 1
          // },
          {
            name: '公司电话',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: '公司电话',
            order: 0,
            isURL: 0
          },
          {
           name: '微信',
           icon: 'wechat',
           href: 'weixin://dl/chat?',
           placeholder: '微信ID',
           value: null,
           label: '微信个人资料ID',
           order: 16,
           isURL: 1
          },
          {
            name: '日历',
            icon: 'calendar',
            placeholder: 'https://example.com/calendarID',
            value: null,
            label: '日历URL',
            order: 17,
            isURL: 1
          },
          {
            name: '客房预订',
            icon: 'store',
            placeholder: 'https://example.com/calendarID',
            value: null,
            label: '客房预订',
            order: 17,
            isURL: 1
          },
          {
            name: 'XMPP',
            icon: 'xmpp',
            href: 'xmpp:',
            placeholder: 'XMPP ID',
            value: null,
            label: 'XMPP ID',
            order: 18,
            isURL: 1
          }
        ],
        secondaryActions: []
      },
      featured: [
        {
          title: '部分标题',
          content: []
        }
      ],
      hostedURL: null,
      footerCredit: false,
      PreviewMode: true,
      content: null,
      inView: false,
      showPreview: false,
      scrollPos: null,
      opening: false
    }
  },
  computed: {
    ...mapState(['theme']),
    getFullname() {
      let fn = this.genInfo.fname
      let ln = this.genInfo.lname
      return (fn + ln).length ? `${fn ? fn : ''}${ln ? ' ' + ln : ''}` : null
    },
    pubKeyIsValid() {
      if (this.genInfo.key) {
        if (!this.genInfo.key.match(/^(-----BEGIN PGP PUBLIC KEY BLOCK-----)/))
          return false

        if (!this.genInfo.key.match(/(-----END PGP PUBLIC KEY BLOCK-----)$/))
          return false

        return true
      } else return false
    },
    downloadChecked() {
      return this.downloadCheckList.filter((e) => e.checked).length == 3
    },
    username() {
      return this.getFullname
        ? this.getFullname.toLowerCase().replace(/\W+/g, '')
        : '用户名'
    },
    orderedPrimaryActions() {
      return this.actions.primaryActions.sort((a, b) =>
        a.order > b.order ? 1 : a.order < b.order ? -1 : 0
      )
    },
    filteredPrimaryActions() {
      return this.orderedPrimaryActions.filter((e) =>
        e.name.toLowerCase().includes(this.filterPrimary.toLowerCase())
      )
    },
    orderedSecondaryActions() {
      return this.actions.secondaryActions.sort((a, b) =>
        a.name.localeCompare(b.name)
      )
    },
    filteredSecondaryActions() {
      return this.orderedSecondaryActions.filter((e) =>
        e.name.toLowerCase().includes(this.filterSecondary.toLowerCase())
      )
    },
    vCard() {
      const getNumber = (type) => {
        let no = this.primaryActions
          .map((e) => (e.name == type ? e.value : null))
          .filter((e) => e)[0]
        return no ? no.replace(/\s/g, '') : null
      }
      let email = this.primaryActions
        .map((e) => (e.name == '电子邮件' ? e.value : null))
        .filter((e) => e)[0]
      let website = this.primaryActions
        .map((e) => (e.name == '网站' ? e.value : null))
        .filter((e) => e)[0]
      let actions = [
        ...this.primaryActions,
        ...this.secondaryActions.map((e) => {
          return { ...e, isURL: 1 }
        })
      ]
      let urls = actions
        .map((e) => {
          if (e.isURL && e.value) {
            return {
              title: e.name,
              url:
                (e.href ? e.href : '') + e.value + (e.hrefEnd ? e.hrefEnd : '')
            }
          }
          return false
        })
        .filter((e) => e)

      let note = this.genInfo.desc
        ? this.genInfo.desc.replace(/[\r\n]+/gm, '')
        : null
      let key = this.pubKeyIsValid ? window.btoa(this.genInfo.key) : null
      let randomNumber = Math.floor(100000000 + Math.random() * 900000)
      return {
        fn: this.genInfo.fname,
        ln: this.genInfo.lname,
        title: this.genInfo.title,
        org: this.genInfo.biz,
        addr: this.genInfo.addr,
        cell: getNumber('手机'),
        work: getNumber('办公室'),
        home: getNumber('家庭'),
        sms: getNumber('短信'),
        email,
        hostedURL: this.hostedURL,
        website,
        urls,
        key,
        note,
        uid: `EnBizCard-${randomNumber}`
      }
    }
  },
  // watch: {
  //   '$route.query': {
  //     handler(newQuery) {
  //       // Handle query parameters when they change
  //       // this.handleQueryParams(newQuery);
  //     },
  //     immediate: true,
  //   },
  // },
  methods: {
    // ...mapActions(['changeTheme']),
    togglePreview() {
      this.opening = true
      let c = this.$refs.container
      if (this.showPreview) {
        c.classList.remove('overflow-y-hidden', 'h-screen')
        window.scrollTo(0, this.scrollPos)
        this.opening = false
      } else {
        this.scrollPos = window.scrollY
        setTimeout(() => {
          c.classList.add('overflow-y-hidden', 'h-screen')
          this.opening = false
        }, 400)
      }
      this.showPreview = !this.showPreview
    },
    checkView() {
      let e = this.$refs.create
      if (e) {
        let top = e.getBoundingClientRect().top
        this.inView = this.showPreview ? true : top < 0
      }
    },
    async saveValue() {
      try {
        if (this.id) {
          await cardService.updateCard(this.$data)
          this.$toast.success('名片更新成功！')
        } else {
          const res = await cardService.saveCard(this.$data)
          this.id = res.data.data.id
          this.$toast.success('名片创建成功！')
          this.$router.push(`/edit/${this.id}`)
        }
      } catch (error) {
        this.$toast.error('操作失败：' + (error.message || '未知错误'))
        console.error('保存失败:', error)
      }
    },
    async initValue(id) {
      try {
        const res = await cardService.getCard(id)
        const value = res.data.data.value
        if (value) {
          console.log('Received data:', value)
          Object.keys(value).forEach(key => {
            if (this.$data.hasOwnProperty(key)) {
              console.log(`Updating ${key}:`, value[key])
              this.$set(this.$data, key, value[key])
            } else {
              console.log(`Skipping unknown property: ${key}`)
            }
          })
        }
      } catch (error) {
        console.error('Failed to get card data:', error)
      }
    },
    save() {
      let e = this.$refs.create
      if (e) {
        let top = e.getBoundingClientRect().top
        this.inView = this.showPreview ? true : top < 0
      }
    },
    clearContent() {
      this.content = null
    },
    create() {
      this.$refs.create.scrollIntoView({ behavior: 'smooth' })
    },
    getTitle(e) {
      return e.toLowerCase().split(' ').join('_')
    },
    addFeature() {
      this.featured.push({
        title: '部分标题',
        content: []
      })
    },
    hasLightBG(e) {
      let hex = this.colors[e].color
      hex = hex.slice(1)
      if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
      }
      let r = parseInt(hex.slice(0, 2), 16)
      let g = parseInt(hex.slice(2, 4), 16)
      let b = parseInt(hex.slice(4, 6), 16)
      const brightness = Math.round(
        (parseInt(r) * 299 + parseInt(g) * 587 + parseInt(b) * 114) / 1000
      )
      return brightness > 125 ? true : false
    },
    showAlert(content) {
      this.content = content
    },
    clearFilterActions() {
      this.filterPrimary = this.filterSecondary = ''
    },
    filteredAction(filterType, actionType) {
      if (this[filterType].length)
        this.addAction(actionType, this[filterType][0].name)
      this.clearFilterActions()
    },
    addAction(type, name) {
      let index = this.actions[type].findIndex((e) => e.name === name)
      this[type].push(this.actions[type][index])
      this.actions[type].splice(index, 1)
    },
    removeAction(type, index) {
      this.actions[type].unshift(this[type][index])
      this[type].splice(index, 1)
    },
    downloadVcard() {
      let blob = new Blob([this.$refs.vCard.$refs.vCard.innerText], {
        type: 'text/plain'
      })
      saveAs(window.URL.createObjectURL(blob), `${this.username}.vcf`)
    },
    downloadKey() {
      let blob = new Blob([this.genInfo.key], {
        type: 'text/plain'
      })
      saveAs(
        window.URL.createObjectURL(blob),
        `${this.getFullname}'s public key.asc`
      )
    },
    async resizeImage(type, mime, index1, index2) {
      let vm = this
      let reader = new FileReader()
      let file
      if (index2 >= 0) {
        if (type == 'image') {
          file = await this.featured[index1].content[index2].file
        } else if (type == 'music') {
          file = await this.featured[index1].content[index2].cover
        } else if (type == 'product') {
          file = await this.featured[index1].content[index2].image.file
        }
      } else {
        file = await this.images[type].blob
      }
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let img = document.createElement('img')
      let maxWidth, maxHeight
      reader.onload = (e) => {
        img.src = e.target.result
        img.onload = () => {
          if (type == 'photo') {
            canvas.width = canvas.height = 320
          } else {
            if (type == 'logo') {
              maxWidth = 960
              maxHeight = 192
            } else if (type == 'cover') {
              maxWidth = 960
              maxHeight = 540
            } else {
              maxWidth = maxHeight = 960
            }
            let width = img.width
            let height = img.height

            if (width > maxWidth) {
              height *= maxWidth / width
              width = maxWidth
            }
            if (height > maxHeight) {
              width *= maxHeight / height
              height = maxHeight
            }
            canvas.width = width
            canvas.height = height
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          canvas.toBlob(
            async (blob) => {
              let image = new File([blob], type, {
                type: mime
              })

              try {
                // 创建 FormData 对象
                const formData = new FormData()
                formData.append('file', image)

                // 上传调整大小后的图片
                const response = await axios.post(
                  uploadConfig.uploadUrl,
                  formData,
                  {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                )

                // 检查响应
                if (response.data && response.data.code === 0) {
                  const uploadedUrl = response.data.data.url

                  if (index2 >= 0) {
                    if (type == 'image') {
                      vm.featured[index1].content[index2].file = image
                      vm.featured[index1].content[index2].url = uploadedUrl
                    } else if (type == 'music') {
                      vm.featured[index1].content[index2].cover = image
                      vm.featured[index1].content[index2].coverUrl = uploadedUrl
                    } else if (type == 'product') {
                      vm.featured[index1].content[index2].image.file = image
                      vm.featured[index1].content[index2].image.url = uploadedUrl
                    }
                  } else {
                    vm.images[type].resized = image
                    vm.images[type].url = uploadedUrl
                  }
                } else {
                  console.error('Resize upload failed')
                }
              } catch (error) {
                console.error('Resize upload error:', error)
              }
            },
            mime,
            0.8
          )
        }
      }
      reader.readAsDataURL(file)
    },
    getTrackingCode() {
      let regex = /<script[^<]*<\/script>/g
      let tracker = this.genInfo.tracker
      if (regex.test(tracker)) {
        let scripts = tracker.match(regex)
        let temp = document.createElement('div')
        temp.innerHTML = tracker
        return scripts.length && temp
      }
      return false
    }
  },
  mounted() {
    // 如果没有id或id为new，都当作新建处理
    if (!this.$route.params.id || this.$route.params.id === 'new') {
      this.id = null
      return
    }

    // 否则加载现有名片
    this.id = this.$route.params.id
    this.initValue(this.id)
  },
  validate({ params }) {
    // 允许访问 /edit/ 和 /edit/new 和 /edit/:id
    return true
  },
}
</script>

